package br.com.ordersys.framework.restlayer.async;

import org.springframework.stereotype.Service;

import br.com.ordersys.framework.restlayer.IResponseBody;
import br.com.ordersys.framework.restlayer.RestCall;
import br.com.ordersys.framework.restlayer.RestCallContext;
import br.com.ordersys.framework.restlayer.async.AsyncServicesManager.Task;
import br.com.ordersys.framework.restlayer.async.AsyncServicesManager.TaskStatus;
import br.com.ordersys.framework.utils.BeanUtils;

@Service("asyncutils")
public class AsyncUtilities implements IAsyncUtilities {

	@RestCall(inputTypeClass = AsyncCallID.class)
	@Override
	public IResponseBody getStatus() {
		AsyncCallID id = (AsyncCallID) RestCallContext.get().getInputObject();

		Task t = AsyncServicesManager.getSingleton().getTask(id.getCallId());

		AsyncCallStatus acs = new AsyncCallStatus();

		if (t != null) {
			acs.setStatus(t.getStatus().toString());
			acs.setRunningTime(t.getRunningTime());

			if (t.getStatusDetail() != null) {
				acs.setDetail(BeanUtils.buildMapFromGetters(t.getStatusDetail()));
			}
		} else {
			acs.setStatus(TaskStatus.UNKNOWN.toString());
		}

		return acs;
	}

	@RestCall(inputTypeClass = AsyncCallID.class)
	@Override
	public IResponseBody cancelExecution() {
		AsyncCallID id = (AsyncCallID) RestCallContext.get().getInputObject();

		Task t = AsyncServicesManager.getSingleton().getTask(id.getCallId());

		AsyncCallStatus acs = new AsyncCallStatus();

		if (t != null) {
			acs.setStatus(t.getStatus().toString());
			acs.setRunningTime(t.getRunningTime());

			if (t.getStatusDetail() != null) {
				acs.setDetail(BeanUtils.buildMapFromGetters(t.getStatusDetail()));
			}

			t.cancelCall();
		} else {
			acs.setStatus(TaskStatus.UNKNOWN.toString());
		}

		return acs;
	}

}
